<template>
  <el-dialog :title="title" :visible.sync="visible" v-if="visible">
    <el-form ref="formRef" :model="formData" :rules="rules" label-postion="right" label-width="100px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input placeholder="分类名称" v-model="formData.categoryName"></el-input>
      </el-form-item>
      <el-form-item label="分类简介">
        <el-input type="textarea" :row="3" placeholder="分类简介" v-model="formData.profile"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">可用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const formData = {
  categoryName: '',
  profile: '',
  status: 1,
  categoryId: ''
}
export default {
  name: 'CategoryUpdate',
  data () {
    return {
      title: '添加分类',
      visible: false,
      formData: { ...formData },
      rules: {
        categoryName: [{ required: true, message: '分类名不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (categoryId) {
      this.visible = true
      if (categoryId) {
        this.title = '修改分类'
        this.$http.get(`admin/category/info/${categoryId}`).then(data => {
          this.formData = { ...data.data }
        })
      } else {
        this.title = '添加分类'
        this.formData = { ...formData }
      }
    },
    saveOrUpdate () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$http.post('admin/category/update', this.formData).then(() => {
            this.$alert(`${this.formData.categoryId ? '修改' : '添加'}成功！`, { type: 'success' }).then(() => {
              this.visible = false
              this.$emit('closeWin')
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
